#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>

#ifndef _SHMDATA_H_HEADER
#define _SHMDATA_H_HEADER
 
#define TEXT_SZ 3
struct shared_use_st
{
 int written_s;//作为一个标志，非0：表示可读，0表示可写
 int written_r;
 int text[TEXT_SZ];//记录写入和读取的文本
};
#endif

int main(){
    int a;
    int b;
    int running = 1; //程序是否继续运行的标志
    void *shm = NULL; //分配的共享内存的原始首地址
    struct shared_use_st *shared;
    int shmid;  //共享内存标识符
    int count=0;  
    //创建共享内存
    // shmid = shmget((key_t)2022, sizeof(struct shared_use_st), 0666 | IPC_CREAT);

    shmid = shmget(1000, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
    // printf("shmid = %d", shmid);
    if(shmid == -1){ //创建失败
        fprintf(stderr,"shmind failed\n");
        exit(EXIT_FAILURE);
    }
    shm = shmat(shmid,0,0); //将共享内存连接到当前进程的地址空间
    if(shm == (void*)-1){
        fprintf(stderr,"shmat failed\n");
        exit(EXIT_FAILURE);
    }

    printf("\nMemory attachered");
    //设置共享内存
    shared = (struct shared_use_st*)shm;
    shared->written_s = 0; // 可写
    shared->written_r = 0; //不可读

    while(count<=10){    //向共享内存中写数据
        while(shared->written_s ==1){   //数据还没有被读取，则等待数据被读取,不能向共享内存中写入文本
            sleep(1);
            printf("Waiting......\n");
        }
        //向共享内存中写入数据
        if(shared->written_r != 0) {
            printf("result: %d + %d = %d",shared->text[0],shared->text[1],shared->text[2]);
        }
        printf("\n生成数字:");
        a = rand() % 100;
        b = rand() % 100;
        shared->text[0] = a;
        shared->text[1] = b;
        printf("a: %d  b: %d\n", a, b);
        //写完数据，设置written使共享内存段可读
        shared->written_s = 1; 
        count++;
    }
    //把共享内存从当前进程中分离
    if(shmdt(shm) == -1){
        fprintf(stderr,"shmdt failed\n");
        exit(EXIT_FAILURE);
    }
    sleep(2);
    exit(EXIT_FAILURE);
}